/**
 * 数据同步任务管理页面
 * 提供同步任务的CRUD操作和执行管理功能
 */

import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Input,
  Select,
  Row,
  Col,
  Tag,
  Tooltip,
  Modal,
  Popconfirm,
  Badge,
  Dropdown,
  Progress,
  Typography,
  Divider
} from 'antd';
import type { TableColumnsType, TableProps } from 'antd';
import {
  PlusOutlined,
  ReloadOutlined,
  SearchOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  EditOutlined,
  DeleteOutlined,
  MoreOutlined,
  SyncOutlined,
  FileTextOutlined,
  BarChartOutlined,
  DownloadOutlined
} from '@ant-design/icons';

import { useAuth } from '../contexts/AuthContext';
import { useUniversalNotification } from '../contexts/UniversalNotificationContext';
import { PermissionGuard } from '../components/PermissionGuard';
import { requestGuard } from '../utils/requestGuard';
import { syncApi } from '../services/syncApi';
import { datasourceApi } from '../services/datasourceApi';
import SyncTaskForm from '../components/SyncTaskForm';
import SyncTaskExecuteModal from '../components/SyncTaskExecuteModal';
import { useSyncTaskProgress } from '../hooks/useSyncTaskProgress';
import { globalSyncTaskManager } from '../utils/globalSyncTaskManager';
import { DatabaseTypeLabels } from '../types/datasource';

import type {
  SyncTask,
  SyncTaskQueryParams
} from '../types/sync';
import {
  SyncType,
  TargetType,
  ExecutionStatus,
  SyncTypeLabels,
  TargetTypeLabels,
  ExecutionStatusLabels
} from '../types/sync';
import type { DataSource } from '../types/datasource';

const { Search } = Input;
const { Option } = Select;
const { Text } = Typography;

const SyncTaskManagement: React.FC = () => {
  // 状态管理
  const [syncTasks, setSyncTasks] = useState<SyncTask[]>([]);
  const [datasources, setDatasources] = useState<DataSource[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isExecuteModalVisible, setIsExecuteModalVisible] = useState(false);
  const [editingTask, setEditingTask] = useState<SyncTask | null>(null);
  const [executingTask, setExecutingTask] = useState<SyncTask | null>(null);

  // 查询参数
  const [searchText, setSearchText] = useState('');
  const [selectedSyncType, setSelectedSyncType] = useState<SyncType | undefined>();
  const [selectedTargetType, setSelectedTargetType] = useState<TargetType | undefined>();
  const [selectedStatus, setSelectedStatus] = useState<boolean | undefined>();

  // 分页参数
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number, range: [number, number]) =>
      `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
  });

  // Hooks
  const { hasPermission } = useAuth();
  const { notificationManager } = useUniversalNotification();
  const syncProgressHook = useSyncTaskProgress();
  const isLoadingRef = useRef(false);

  // 跟踪正在运行的同步任务通知ID
  const runningTaskNotifications = useRef<Map<number, string>>(new Map());

  // 权限检查
  const permissions = {
    canView: hasPermission('sync:task:view'),
    canCreate: hasPermission('sync:task:create'),
    canUpdate: hasPermission('sync:task:update'),
    canDelete: hasPermission('sync:task:delete'),
    canExecute: hasPermission('sync:task:execute'),
  };

  /**
   * 获取同步任务列表
   */
  const fetchSyncTasks = useCallback(async (forceRefresh: boolean = false) => {
    const currentParams: SyncTaskQueryParams = {
      page: pagination.current,
      page_size: pagination.pageSize,
      search: searchText || undefined,
      sync_type: selectedSyncType,
      target_type: selectedTargetType,
      is_active: selectedStatus
    };

    // 使用requestGuard防止重复请求
    if (!forceRefresh && !requestGuard.canRequest('fetchSyncTasks', currentParams)) {
      return;
    }

    if (isLoadingRef.current) {
      return;
    }

    try {
      setLoading(true);
      isLoadingRef.current = true;

      const response = await syncApi.getSyncTasks(currentParams);

      setSyncTasks(response.items);
      setPagination(prev => ({
        ...prev,
        total: response.total,
        current: response.page,
        pageSize: response.page_size
      }));

    } catch (error) {
      console.error('获取同步任务列表失败:', error);
    } finally {
      setLoading(false);
      isLoadingRef.current = false;
      requestGuard.completeRequest('fetchSyncTasks');
    }
  }, [pagination.current, pagination.pageSize, searchText, selectedSyncType, selectedTargetType, selectedStatus]);

  /**
   * 获取数据源列表
   */
  const fetchDatasources = useCallback(async () => {
    try {
      const response = await datasourceApi.getDatasources({
        page: 1,
        page_size: 100,
        is_active: true
      });
      setDatasources(response.datasources);
    } catch (error) {
      console.error('获取数据源列表失败:', error);
    }
  }, []);



  /**
   * 触发数据获取的包装函数 - 避免useEffect依赖问题
   */
  const triggerDataFetch = useCallback(() => {
    fetchSyncTasks(true); // 强制刷新，绕过requestGuard
    fetchDatasources();
  }, [fetchSyncTasks, fetchDatasources]);

  /**
   * 初始化数据获取 - 只在组件挂载时执行一次，遵循其他管理页面的模式
   */
  useEffect(() => {
    if (!permissions.canView) return;

    // 清除可能存在的请求防护状态（页面刷新时）
    requestGuard.clearGuard('fetchSyncTasks');

    // 获取数据
    triggerDataFetch();

    // 组件卸载时不取消任务，只清理本地监控状态
    return () => {
      // 不调用 cancelSyncTask，让任务继续在后台运行
      // 只清理本地的监控映射
      runningTaskNotifications.current.clear();
    };
  }, [permissions.canView]); // 移除函数依赖，避免无限循环

  /**
   * 分页和搜索条件变化时获取数据
   */
  useEffect(() => {
    if (!permissions.canView) return;

    fetchSyncTasks();
  }, [permissions.canView, fetchSyncTasks]);

  /**
   * 搜索处理
   */
  const handleSearch = useCallback((value: string) => {
    setSearchText(value);
    setPagination(prev => ({ ...prev, current: 1 }));
  }, []);

  /**
   * 筛选处理
   */
  const handleFilterChange = useCallback((type: string, value: any) => {
    switch (type) {
      case 'syncType':
        setSelectedSyncType(value);
        break;
      case 'targetType':
        setSelectedTargetType(value);
        break;
      case 'status':
        setSelectedStatus(value);
        break;
    }
    setPagination(prev => ({ ...prev, current: 1 }));
  }, []);

  /**
   * 表格变化处理
   */
  const handleTableChange: TableProps<SyncTask>['onChange'] = (paginationConfig) => {
    setPagination(prev => ({
      ...prev,
      current: paginationConfig.current || 1,
      pageSize: paginationConfig.pageSize || 10,
    }));
  };

  /**
   * 行选择处理
   */
  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
    getCheckboxProps: (record: SyncTask) => ({
      disabled: !permissions.canUpdate,
    }),
  };

  /**
   * 打开模态框
   */
  const openModal = (task?: SyncTask) => {
    setEditingTask(task || null);
    setIsModalVisible(true);
  };

  /**
   * 关闭模态框
   */
  const closeModal = () => {
    setIsModalVisible(false);
    setEditingTask(null);
  };

  /**
   * 关闭执行模态框
   */
  const closeExecuteModal = () => {
    setIsExecuteModalVisible(false);
    setExecutingTask(null);
  };

  /**
   * 处理任务执行
   */
  const handleTaskExecution = async (executionRequest: any) => {
    if (!executingTask) return;

    await executeTask(executingTask, executionRequest);
    closeExecuteModal();
  };

  /**
   * 表单提交处理
   */
  const handleSubmit = async (values: any) => {
    try {
      if (editingTask) {
        await syncApi.updateSyncTask(editingTask.id, values);
      } else {
        await syncApi.createSyncTask(values);
      }
      
      closeModal();
      fetchSyncTasks(true);
    } catch (error) {
      console.error('保存同步任务失败:', error);
    }
  };

  /**
   * 删除任务
   */
  const handleDelete = async (taskId: number) => {
    try {
      await syncApi.deleteSyncTask(taskId);
      fetchSyncTasks(true);
    } catch (error) {
      console.error('删除同步任务失败:', error);
    }
  };

  /**
   * 打开执行任务模态框
   */
  const handleExecute = (task: SyncTask) => {
    setExecutingTask(task);
    setIsExecuteModalVisible(true);
  };

  /**
   * 执行任务 - 集成Dynamic Island进度显示
   */
  const executeTask = async (task: SyncTask, executionRequest: any) => {


    try {
      // 检查任务是否已在运行
      if (runningTaskNotifications.current.has(task.id)) {
        console.warn(`任务 ${task.display_name} 已在运行中`);
        return;
      }

      // 获取源数据源和目标类型信息
      const sourceDataSource = datasources.find(ds => ds.id === task.source_datasource_id);
      const sourceTypeRaw = sourceDataSource?.type;
      const sourceType = sourceTypeRaw ? DatabaseTypeLabels[sourceTypeRaw] || sourceTypeRaw : 'Unknown';
      const targetType = task.target_type.toUpperCase();



      const execution = await syncApi.executeSyncTask(task.id, executionRequest);



      // 使用全局监控器来监控任务，这样即使页面切换任务也能继续运行


      const notificationId = globalSyncTaskManager.startTaskMonitoring(
        execution.id,
        task.display_name,
        sourceType,
        targetType
      );

      if (notificationId) {

        // 记录运行中的任务通知映射（用于本地状态管理）
        runningTaskNotifications.current.set(task.id, notificationId);
      } else {

        // 降级到本地监控
        const localNotificationId = syncProgressHook.startSyncTask(
          task.display_name,
          sourceType,
          targetType
        );
        runningTaskNotifications.current.set(task.id, localNotificationId);
      }

      // 如果使用全局监控器，就不需要本地轮询了
      if (globalSyncTaskManager.isTaskMonitoring(execution.id)) {

        return;
      }

      // 降级情况：使用本地轮询

      const startTime = Date.now();

      // 轮询执行进度 - 使用新的进度更新方法
      syncApi.pollExecutionProgress(execution.id, (updatedExecution) => {
        // 确保进度是数字类型
        const progress = typeof updatedExecution.progress_percentage === 'string'
          ? parseFloat(updatedExecution.progress_percentage)
          : (updatedExecution.progress_percentage || 0);
        const processedRecords = updatedExecution.processed_records || 0;
        const totalRecords = updatedExecution.total_records || 0;



        // 计算当前阶段描述（简洁显示）
        let currentStage = '初始化';
        if (progress > 0 && progress < 20) {
          currentStage = '连接数据源';
        } else if (progress >= 20 && progress < 40) {
          currentStage = '读取数据';
        } else if (progress >= 40 && progress < 70) {
          currentStage = '处理数据';
        } else if (progress >= 70 && progress < 90) {
          currentStage = '写入数据';
        } else if (progress >= 90) {
          currentStage = '验证完成';
        }

        // 计算预计剩余时间
        const elapsedTime = Date.now() - startTime;
        const estimatedTotalTime = progress > 0 ? (elapsedTime / progress) * 100 : 0;
        const estimatedTimeRemaining = Math.max(0, estimatedTotalTime - elapsedTime);

        // 更新Dynamic Island进度
        syncProgressHook.updateSyncProgress(
          notificationId,
          progress,
          currentStage,
          processedRecords,
          totalRecords,
          {
            successRecords: updatedExecution.success_records || 0,
            failedRecords: updatedExecution.failed_records || 0,
            estimatedTimeRemaining: Math.round(estimatedTimeRemaining / 1000), // 转换为秒
            currentBatch: updatedExecution.current_batch || 0,
            totalBatches: updatedExecution.total_batches || 0,
            executionId: execution.id,
            taskId: task.id,
            taskName: task.display_name,
            sourceType,
            targetType
          }
        );

        // 检查任务是否完成（只处理真正的完成状态）
        const completedStatuses = ['success', 'failed', 'cancelled'];
        if (completedStatuses.includes(updatedExecution.status)) {
          const success = updatedExecution.status === 'success';
          const duration = Date.now() - startTime;



          // 完成Dynamic Island通知
          const summary = success
            ? `同步完成：处理 ${processedRecords} 条记录，成功 ${updatedExecution.success_records || 0} 条`
            : `同步失败：已处理 ${processedRecords} 条记录`;

          syncProgressHook.completeSyncTask(
            notificationId,
            success,
            summary,
            {
              processedRecords,
              successRecords: updatedExecution.success_records || 0,
              failedRecords: updatedExecution.failed_records || 0,
              totalRecords,
              duration: Math.round(duration / 1000), // 转换为秒
              executionId: execution.id,
              taskId: task.id
            }
          );

          // 清理运行中任务记录
          runningTaskNotifications.current.delete(task.id);
        }
      });

      fetchSyncTasks(true);
    } catch (error) {
      console.error('执行同步任务失败:', error);

      // 如果启动失败，清理通知记录
      const notificationId = runningTaskNotifications.current.get(task.id);

      if (notificationId) {
        syncProgressHook.failSyncTask(notificationId, {
          message: error instanceof Error ? error.message : '任务启动失败',
          code: 'EXECUTION_START_FAILED',
          details: error
        });
        runningTaskNotifications.current.delete(task.id);
      }
    }
  };

  /**
   * 切换任务状态
   */
  const handleToggleStatus = async (task: SyncTask) => {
    try {
      if (task.is_active) {
        await syncApi.disableSyncTask(task.id);
      } else {
        await syncApi.enableSyncTask(task.id);
      }
      fetchSyncTasks(true);
    } catch (error) {
      console.error('切换任务状态失败:', error);
    }
  };

  /**
   * 获取执行状态标签
   */
  const getExecutionStatusTag = (status?: ExecutionStatus) => {
    if (!status) return null;

    const statusConfig = {
      pending: { color: 'default', text: ExecutionStatusLabels.pending },
      running: { color: 'processing', text: ExecutionStatusLabels.running },
      success: { color: 'success', text: ExecutionStatusLabels.success },
      failed: { color: 'error', text: ExecutionStatusLabels.failed },
      paused: { color: 'warning', text: ExecutionStatusLabels.paused },
      cancelled: { color: 'default', text: ExecutionStatusLabels.cancelled },
    };

    const config = statusConfig[status];
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  /**
   * 批量执行任务 - 支持多任务并发监控
   */
  const handleBatchExecute = async (taskIds: number[]) => {
    try {
      // 过滤掉已在运行的任务
      const availableTaskIds = taskIds.filter(taskId => !runningTaskNotifications.current.has(taskId));

      if (availableTaskIds.length === 0) {
        console.warn('所有选中的任务都已在运行中');
        return;
      }

      if (availableTaskIds.length !== taskIds.length) {
        console.warn(`${taskIds.length - availableTaskIds.length} 个任务已在运行中，将执行其余 ${availableTaskIds.length} 个任务`);
      }

      // 获取任务详情
      const tasksToExecute = syncTasks.filter(task => availableTaskIds.includes(task.id));

      // 并发执行所有任务（使用默认参数）
      const executePromises = tasksToExecute.map(task =>
        executeTask(task, { execution_params: {}, force_full_sync: false })
      );
      await Promise.allSettled(executePromises);

      console.log(`批量执行完成：启动了 ${availableTaskIds.length} 个同步任务`);
    } catch (error) {
      console.error('批量执行任务失败:', error);
    }
  };

  /**
   * 下载CSV文件
   */
  const handleDownloadCsv = async (task: SyncTask) => {
    try {
      await syncApi.downloadCsvFile(task.id);
    } catch (error) {
      console.error('下载CSV文件失败:', error);
    }
  };

  // 表格列定义
  const columns: TableColumnsType<SyncTask> = [
    {
      title: '任务名称',
      dataIndex: 'display_name',
      key: 'display_name',
      width: 200,
      render: (text: string, record: SyncTask) => (
        <div>
          <div style={{ fontWeight: 500 }}>{text}</div>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            {record.name}
          </Text>
        </div>
      ),
    },
    {
      title: '同步类型',
      dataIndex: 'sync_type',
      key: 'sync_type',
      width: 100,
      render: (syncType: SyncType) => (
        <Tag color={syncType === SyncType.FULL ? 'blue' : 'green'}>
          {SyncTypeLabels[syncType]}
        </Tag>
      ),
    },
    {
      title: '目标类型',
      dataIndex: 'target_type',
      key: 'target_type',
      width: 120,
      render: (targetType: TargetType) => (
        <Tag color="purple">{TargetTypeLabels[targetType]}</Tag>
      ),
    },
    {
      title: '状态',
      key: 'status',
      width: 120,
      render: (_, record: SyncTask) => (
        <Space direction="vertical" size={4}>
          <Tag color={record.is_active ? 'success' : 'default'}>
            {record.is_active ? '启用' : '禁用'}
          </Tag>
          {getExecutionStatusTag(record.last_execution_status)}
        </Space>
      ),
    },
    {
      title: '最后执行',
      dataIndex: 'last_execution_time',
      key: 'last_execution_time',
      width: 160,
      render: (time: string) => time ? new Date(time).toLocaleString() : '-',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 160,
      render: (time: string) => new Date(time).toLocaleString(),
    },
    {
      title: '操作',
      key: 'actions',
      width: 240,
      fixed: 'right',
      render: (_, record: SyncTask) => (
        <Space size="small">
          <PermissionGuard permission="sync:task:execute">
            <Tooltip title="执行任务">
              <Button
                type="text"
                size="small"
                icon={<PlayCircleOutlined />}
                onClick={() => handleExecute(record)}
                disabled={!record.is_active}
              />
            </Tooltip>
          </PermissionGuard>

          {/* CSV下载按钮 */}
          {record.target_type === TargetType.CSV && (
            <PermissionGuard permission="sync:task:view">
              <Tooltip title="下载CSV文件">
                <Button
                  type="text"
                  size="small"
                  icon={<DownloadOutlined />}
                  onClick={() => handleDownloadCsv(record)}
                  disabled={!record.last_execution_time || record.last_execution_status !== ExecutionStatus.SUCCESS}
                />
              </Tooltip>
            </PermissionGuard>
          )}

          <PermissionGuard permission="sync:task:update">
            <Tooltip title="编辑">
              <Button
                type="text"
                size="small"
                icon={<EditOutlined />}
                onClick={() => openModal(record)}
              />
            </Tooltip>
          </PermissionGuard>

          <PermissionGuard permission="sync:task:delete">
            <Popconfirm
              title="确认删除"
              description={`确定要删除同步任务"${record.display_name}"吗？`}
              onConfirm={() => handleDelete(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Tooltip title="删除">
                <Button
                  type="text"
                  size="small"
                  danger
                  icon={<DeleteOutlined />}
                />
              </Tooltip>
            </Popconfirm>
          </PermissionGuard>

          <Dropdown
            menu={{
              items: [
                {
                  key: 'toggle',
                  label: record.is_active ? '禁用' : '启用',
                  icon: record.is_active ? <PauseCircleOutlined /> : <PlayCircleOutlined />,
                  onClick: () => handleToggleStatus(record),
                  disabled: !permissions.canUpdate
                },
                {
                  key: 'logs',
                  label: '查看日志',
                  icon: <FileTextOutlined />,
                  onClick: () => {
                    // TODO: 打开日志查看页面
                  }
                }
              ]
            }}
            trigger={['click']}
          >
            <Button type="text" size="small" icon={<MoreOutlined />} />
          </Dropdown>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 搜索和筛选 */}
      <Card style={{ marginBottom: 16 }}>
        <Row gutter={16} align="middle">
          <Col flex="auto">
            <Space wrap>
              <Search
                placeholder="搜索任务名称、描述"
                allowClear
                style={{ width: 300 }}
                onSearch={handleSearch}
                enterButton={<SearchOutlined />}
              />

              <Select
                placeholder="同步类型"
                allowClear
                style={{ width: 120 }}
                value={selectedSyncType}
                onChange={(value) => handleFilterChange('syncType', value)}
              >
                {Object.entries(SyncTypeLabels).map(([key, label]) => (
                  <Option key={key} value={key}>{label}</Option>
                ))}
              </Select>

              <Select
                placeholder="目标类型"
                allowClear
                style={{ width: 140 }}
                value={selectedTargetType}
                onChange={(value) => handleFilterChange('targetType', value)}
              >
                {Object.entries(TargetTypeLabels).map(([key, label]) => (
                  <Option key={key} value={key}>{label}</Option>
                ))}
              </Select>

              <Select
                placeholder="状态"
                allowClear
                style={{ width: 100 }}
                value={selectedStatus}
                onChange={(value) => handleFilterChange('status', value)}
              >
                <Option value={true}>启用</Option>
                <Option value={false}>禁用</Option>
              </Select>
            </Space>
          </Col>

          <Col>
            <Space>
              {/* 批量操作 */}
              {selectedRowKeys.length > 0 && (
                <Badge count={selectedRowKeys.length} size="small">
                  <Dropdown
                    menu={{
                      items: [
                        {
                          key: 'batchEnable',
                          label: '批量启用',
                          onClick: () => syncApi.batchEnableSyncTasks(selectedRowKeys as number[])
                        },
                        {
                          key: 'batchDisable',
                          label: '批量禁用',
                          onClick: () => syncApi.batchDisableSyncTasks(selectedRowKeys as number[])
                        },
                        {
                          key: 'batchExecute',
                          label: '批量执行',
                          onClick: () => handleBatchExecute(selectedRowKeys as number[])
                        },
                        { type: 'divider' },
                        {
                          key: 'batchDelete',
                          label: '批量删除',
                          danger: true,
                          onClick: () => syncApi.batchDeleteSyncTasks(selectedRowKeys as number[])
                        }
                      ]
                    }}
                    trigger={['click']}
                  >
                    <Button>
                      批量操作 <MoreOutlined />
                    </Button>
                  </Dropdown>
                </Badge>
              )}

              {/* 刷新按钮 */}
              <Button
                icon={<ReloadOutlined />}
                onClick={() => fetchSyncTasks(true)}
                loading={loading}
              >
                刷新
              </Button>

              {/* 创建按钮 */}
              <PermissionGuard permission="sync:task:create">
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() => openModal()}
                >
                  新建同步任务
                </Button>
              </PermissionGuard>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 数据表格 */}
      <Card>
        <Table<SyncTask>
          columns={columns}
          dataSource={syncTasks}
          rowKey="id"
          loading={loading}
          rowSelection={rowSelection}
          pagination={pagination}
          onChange={handleTableChange}
          scroll={{ x: 1400 }}
          size="middle"
        />
      </Card>

      {/* 创建/编辑模态框 */}
      <Modal
        title={
          <Space>
            <SyncOutlined />
            {editingTask ? '编辑同步任务' : '新建同步任务'}
          </Space>
        }
        open={isModalVisible}
        onCancel={closeModal}
        footer={null}
        width={1000}
        destroyOnClose
      >
        <SyncTaskForm
          task={editingTask || undefined}
          datasources={datasources}
          onSubmit={handleSubmit}
          onCancel={closeModal}
          loading={loading}
        />
      </Modal>

      {/* 执行任务模态框 */}
      <SyncTaskExecuteModal
        visible={isExecuteModalVisible}
        task={executingTask}
        loading={loading}
        onExecute={handleTaskExecution}
        onCancel={closeExecuteModal}
      />
    </div>
  );
};

export default SyncTaskManagement;
